<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon.ico">
  <link rel="mask-icon" href="/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-5eIC48iZUHmSlSUz9XtjRyK2mzQkHScZY1WdMaoz74E=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.dqv5.com","root":"/","images":"/images","scheme":"Mist","darkmode":true,"version":"8.21.1","exturl":false,"sidebar":{"position":"right","width_expanded":320,"width_dual_column":240,"display":"always","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":null},"fold":{"enable":true,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="AES、RSA加密解密方法在Java和JavaScript中的实现代码">
<meta property="og:type" content="article">
<meta property="og:title" content="AES、RSA加密解密方法实现">
<meta property="og:url" content="http://blog.dqv5.com/2022/12/14/encrypt-decrypt/index.html">
<meta property="og:site_name" content="dqv5.com">
<meta property="og:description" content="AES、RSA加密解密方法在Java和JavaScript中的实现代码">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-14T14:05:11.000Z">
<meta property="article:modified_time" content="2024-11-23T11:58:37.867Z">
<meta property="article:author" content="du qian">
<meta property="article:tag" content="加密">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://blog.dqv5.com/2022/12/14/encrypt-decrypt/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.dqv5.com/2022/12/14/encrypt-decrypt/","path":"2022/12/14/encrypt-decrypt/","title":"AES、RSA加密解密方法实现"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>AES、RSA加密解密方法实现 | dqv5.com</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?1752ae624eedea5ce859335ad2f0e657"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">dqv5.com</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">49</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">20</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a></li><li class="menu-item menu-item-留言板"><a href="/message-board/" rel="section"><i class="fa fa-comments fa-fw"></i>留言板</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-AES%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%EF%BC%88Java%EF%BC%89"><span class="nav-text">1. AES加密解密（Java）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-AES%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%EF%BC%88JavaScript%EF%BC%89"><span class="nav-text">2. AES加密解密（JavaScript）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-RSA%E5%AF%86%E9%92%A5%E7%94%9F%E6%88%90%EF%BC%88Linux%E5%91%BD%E4%BB%A4%E8%A1%8C%EF%BC%89"><span class="nav-text">3. RSA密钥生成（Linux命令行）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%EF%BC%88Java%EF%BC%89"><span class="nav-text">4. RSA加密解密（Java）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86%EF%BC%88JavaScript%EF%BC%89"><span class="nav-text">5. RSA加密解密（JavaScript）</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="du qian"
      src="/images/soccer.jpg">
  <p class="site-author-name" itemprop="name">du qian</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">20</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">49</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/duqian42707" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://stackoverflow.com/duqian42707" title="StackOverflow → https:&#x2F;&#x2F;stackoverflow.com&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fab fa-stack-overflow fa-fw"></i>StackOverflow</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/duqian42707" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;duqian42707" rel="noopener me" target="_blank"><i class="fas fa-link fa-fw"></i>CSDN</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://duqian42707.github.io/qiniu-host" title="图床 → https:&#x2F;&#x2F;duqian42707.github.io&#x2F;qiniu-host" rel="noopener me" target="_blank"><i class="far fa-image fa-fw"></i>图床</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.dqv5.com/2022/12/14/encrypt-decrypt/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/soccer.jpg">
      <meta itemprop="name" content="du qian">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="dqv5.com">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="AES、RSA加密解密方法实现 | dqv5.com">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          AES、RSA加密解密方法实现
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-12-14 14:05:11" itemprop="dateCreated datePublished" datetime="2022-12-14T14:05:11+00:00">2022-12-14</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2024-11-23 11:58:37" itemprop="dateModified" datetime="2024-11-23T11:58:37+00:00">2024-11-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>摘要：AES、RSA加密解密方法在Java和JavaScript中的实现代码</p>
<!-- more -->

<h2 id="1-AES加密解密（Java）"><a href="#1-AES加密解密（Java）" class="headerlink" title="1. AES加密解密（Java）"></a>1. AES加密解密（Java）</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.crypto.*;</span><br><span class="line"><span class="keyword">import</span> javax.crypto.spec.IvParameterSpec;</span><br><span class="line"><span class="keyword">import</span> javax.crypto.spec.SecretKeySpec;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.security.InvalidAlgorithmParameterException;</span><br><span class="line"><span class="keyword">import</span> java.security.InvalidKeyException;</span><br><span class="line"><span class="keyword">import</span> java.security.NoSuchAlgorithmException;</span><br><span class="line"><span class="keyword">import</span> java.util.Base64;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> duqian</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AESEncryptUtils</span> &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * AES加密</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> input     明文</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> keyString 密钥,16位英文+数字</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ivString  偏移量,16位英文+数字</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">encrypt</span><span class="params">(String input, String keyString, String ivString)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">SecretKey</span> <span class="variable">key</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SecretKeySpec</span>(keyString.getBytes(StandardCharsets.UTF_8), <span class="string">&quot;AES&quot;</span>);</span><br><span class="line">            <span class="type">IvParameterSpec</span> <span class="variable">iv</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">IvParameterSpec</span>(ivString.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            <span class="type">Cipher</span> <span class="variable">cipher</span> <span class="operator">=</span> Cipher.getInstance(<span class="string">&quot;AES/CBC/PKCS5Padding&quot;</span>);</span><br><span class="line">            cipher.init(Cipher.ENCRYPT_MODE, key, iv);</span><br><span class="line">            <span class="type">byte</span>[] cipherText = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));</span><br><span class="line">            <span class="keyword">return</span> Base64.getEncoder().encodeToString(cipherText);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException |</span><br><span class="line">                 NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * AES解密</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cipherText 密文</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> keyString  密钥,16位英文+数字</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> ivString   偏移量,16位英文+数字</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">decrypt</span><span class="params">(String cipherText, String keyString, String ivString)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="type">SecretKey</span> <span class="variable">key</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">SecretKeySpec</span>(keyString.getBytes(StandardCharsets.UTF_8), <span class="string">&quot;AES&quot;</span>);</span><br><span class="line">            <span class="type">IvParameterSpec</span> <span class="variable">iv</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">IvParameterSpec</span>(ivString.getBytes(StandardCharsets.UTF_8));</span><br><span class="line"></span><br><span class="line">            <span class="type">Cipher</span> <span class="variable">cipher</span> <span class="operator">=</span> Cipher.getInstance(<span class="string">&quot;AES/CBC/PKCS5Padding&quot;</span>);</span><br><span class="line">            cipher.init(Cipher.DECRYPT_MODE, key, iv);</span><br><span class="line">            <span class="type">byte</span>[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">String</span>(plainText, StandardCharsets.UTF_8);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InvalidAlgorithmParameterException | NoSuchPaddingException | IllegalBlockSizeException |</span><br><span class="line">                 NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">// 密钥-16位字符串形式</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">keyString</span> <span class="operator">=</span> <span class="string">&quot;1234EFghiJklmn56&quot;</span>;</span><br><span class="line">        <span class="comment">// 偏移量-16位字符串形式</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">ivString</span> <span class="operator">=</span> <span class="string">&quot;abcdEFG890123456&quot;</span>;</span><br><span class="line">        <span class="comment">// 明文字符串</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">plainText</span> <span class="operator">=</span> <span class="string">&quot;阿斯蒂芬中文www.baeldung.com符号！@#%……）（*&amp;… …%-——+=)(&amp;^%$#/*-\\|123a阿斯蒂芬&quot;</span>;</span><br><span class="line">        log.info(<span class="string">&quot;plainText:\t\t\t\t&#123;&#125;&quot;</span>, plainText);</span><br><span class="line">        <span class="comment">// 加密</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">cipherText</span> <span class="operator">=</span> AESEncryptUtils.encrypt(plainText, keyString, ivString);</span><br><span class="line">        log.info(<span class="string">&quot;cipherText:\t\t\t&#123;&#125;&quot;</span>, cipherText);</span><br><span class="line">        <span class="comment">// 解密</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">decryptedCipherText</span> <span class="operator">=</span> AESEncryptUtils.decrypt(cipherText, keyString, ivString);</span><br><span class="line">        log.info(<span class="string">&quot;decryptedCipherText:\t&#123;&#125;&quot;</span>, decryptedCipherText);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-AES加密解密（JavaScript）"><a href="#2-AES加密解密（JavaScript）" class="headerlink" title="2. AES加密解密（JavaScript）"></a>2. AES加密解密（JavaScript）</h2><p>安装依赖</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install crypto-js</span><br></pre></td></tr></table></figure>

<p>使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * AES加密</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> word 需要加密的字符</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> key 秘钥</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> iv 偏移量</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">aesEncrypt</span>(<span class="params">word, key, iv</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> _word = <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>.<span class="title function_">parse</span>(word);</span><br><span class="line">  <span class="keyword">const</span> _key = <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>.<span class="title function_">parse</span>(key);</span><br><span class="line">  <span class="keyword">const</span> _iv = <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>.<span class="title function_">parse</span>(iv);</span><br><span class="line">  <span class="keyword">const</span> encrypted = <span class="title class_">CryptoJS</span>.<span class="property">AES</span>.<span class="title function_">encrypt</span>(_word, _key, &#123;</span><br><span class="line">    <span class="attr">iv</span>: _iv,</span><br><span class="line">    <span class="attr">mode</span>: <span class="title class_">CryptoJS</span>.<span class="property">mode</span>.<span class="property">CBC</span>,</span><br><span class="line">    <span class="attr">padding</span>: <span class="title class_">CryptoJS</span>.<span class="property">pad</span>.<span class="property">Pkcs7</span></span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> encrypted.<span class="title function_">toString</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * AES解密</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> word 需要解密的字符</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> key 秘钥</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> iv 偏移量</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">aesDecrypt</span>(<span class="params">word, key, iv</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> _word = &#123;<span class="attr">ciphertext</span>: <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Base64</span>.<span class="title function_">parse</span>(word)&#125;;</span><br><span class="line">  <span class="keyword">const</span> _key = <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>.<span class="title function_">parse</span>(key);</span><br><span class="line">  <span class="keyword">const</span> _iv = <span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>.<span class="title function_">parse</span>(iv);</span><br><span class="line">  <span class="keyword">const</span> decrypted = <span class="title class_">CryptoJS</span>.<span class="property">AES</span>.<span class="title function_">decrypt</span>(_word, _key, &#123;</span><br><span class="line">    <span class="attr">iv</span>: _iv,</span><br><span class="line">    <span class="attr">mode</span>: <span class="title class_">CryptoJS</span>.<span class="property">mode</span>.<span class="property">CBC</span>,</span><br><span class="line">    <span class="attr">padding</span>: <span class="title class_">CryptoJS</span>.<span class="property">pad</span>.<span class="property">Pkcs7</span></span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> decrypted.<span class="title function_">toString</span>(<span class="title class_">CryptoJS</span>.<span class="property">enc</span>.<span class="property">Utf8</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">aesMain</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> key = <span class="string">&#x27;1234EFghiJklmn56&#x27;</span>;</span><br><span class="line">  <span class="keyword">const</span> iv = <span class="string">&#x27;abcdEFG890123456&#x27;</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> text = <span class="string">&quot;阿什顿发asdfa1231@#$%^&amp;*(阿道夫（*……%￥%……&amp;asd安抚&quot;</span>;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[AES]明文: &#x27;</span> + text);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> encrypted = <span class="title function_">aesEncrypt</span>(text, key, iv);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[AES]密文: &#x27;</span> + encrypted);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> decrypted = <span class="title function_">aesDecrypt</span>(encrypted, key, iv);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[AES]解密: &#x27;</span> + decrypted);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">aesMain</span>();</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="3-RSA密钥生成（Linux命令行）"><a href="#3-RSA密钥生成（Linux命令行）" class="headerlink" title="3. RSA密钥生成（Linux命令行）"></a>3. RSA密钥生成（Linux命令行）</h2><p>详见：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/c93a993f8997">https://www.jianshu.com/p/c93a993f8997</a></p>
<p>生成私钥(PKCS#1)</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl genrsa -out private_key.pem 1024</span><br></pre></td></tr></table></figure>

<p>提取公钥</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl rsa -pubout -<span class="keyword">in</span> private_key.pem -out public_key.pem</span><br></pre></td></tr></table></figure>

<p>RSA私钥格式转换（PKCS#1 &#x3D;&#x3D;&gt; PKCS#8）</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">openssl pkcs8 -topk8 -inform PEM -<span class="keyword">in</span> private_key.pem -outform PEM -out private_key_pkcs8.pem -nocrypt</span><br></pre></td></tr></table></figure>

<h2 id="4-RSA加密解密（Java）"><a href="#4-RSA加密解密（Java）" class="headerlink" title="4. RSA加密解密（Java）"></a>4. RSA加密解密（Java）</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.extern.slf4j.Slf4j;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.crypto.BadPaddingException;</span><br><span class="line"><span class="keyword">import</span> javax.crypto.Cipher;</span><br><span class="line"><span class="keyword">import</span> javax.crypto.IllegalBlockSizeException;</span><br><span class="line"><span class="keyword">import</span> javax.crypto.NoSuchPaddingException;</span><br><span class="line"><span class="keyword">import</span> java.nio.charset.StandardCharsets;</span><br><span class="line"><span class="keyword">import</span> java.security.*;</span><br><span class="line"><span class="keyword">import</span> java.security.interfaces.RSAPrivateKey;</span><br><span class="line"><span class="keyword">import</span> java.security.interfaces.RSAPublicKey;</span><br><span class="line"><span class="keyword">import</span> java.security.spec.InvalidKeySpecException;</span><br><span class="line"><span class="keyword">import</span> java.security.spec.PKCS8EncodedKeySpec;</span><br><span class="line"><span class="keyword">import</span> java.security.spec.X509EncodedKeySpec;</span><br><span class="line"><span class="keyword">import</span> java.util.Base64;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> duqian</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 命令行生成RSA密钥</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 生成私钥(PKCS#1)：</span></span><br><span class="line"><span class="comment"> * openssl genrsa -out private_key.pem 1024</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * 提取公钥：</span></span><br><span class="line"><span class="comment"> * openssl rsa -pubout -in private_key.pem -out public_key.pem</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * RSA私钥格式转换（PKCS#1 ==&gt; PKCS#8）：</span></span><br><span class="line"><span class="comment"> * openssl pkcs8 -topk8 -inform PEM -in private_key.pem -outform PEM -out private_key_pkcs8.pem -nocrypt</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RSAEncryptUtils</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * RSA公钥加密</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> str       加密字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> publicKey 公钥</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 密文</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">encrypt</span><span class="params">(String str, String publicKey)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// base64编码的公钥</span></span><br><span class="line">            <span class="type">byte</span>[] decoded = Base64.getDecoder().decode(publicKey);</span><br><span class="line">            <span class="type">RSAPublicKey</span> <span class="variable">pubKey</span> <span class="operator">=</span> (RSAPublicKey) KeyFactory.getInstance(<span class="string">&quot;RSA&quot;</span>).generatePublic(<span class="keyword">new</span> <span class="title class_">X509EncodedKeySpec</span>(decoded));</span><br><span class="line">            <span class="comment">// RSA加密</span></span><br><span class="line">            <span class="type">Cipher</span> <span class="variable">cipher</span> <span class="operator">=</span> Cipher.getInstance(<span class="string">&quot;RSA&quot;</span>);</span><br><span class="line">            cipher.init(Cipher.ENCRYPT_MODE, pubKey);</span><br><span class="line">            <span class="type">byte</span>[] cipherText = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));</span><br><span class="line">            <span class="keyword">return</span> Base64.getEncoder().encodeToString(cipherText);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException | NoSuchPaddingException | IllegalBlockSizeException |</span><br><span class="line">                 InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * RSA私钥解密</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> str        加密字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> privateKey 私钥</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 明文</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">decrypt</span><span class="params">(String str, String privateKey)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// base64编码的私钥</span></span><br><span class="line">            <span class="type">byte</span>[] decoded = Base64.getDecoder().decode(privateKey);</span><br><span class="line">            <span class="type">RSAPrivateKey</span> <span class="variable">priKey</span> <span class="operator">=</span> (RSAPrivateKey) KeyFactory.getInstance(<span class="string">&quot;RSA&quot;</span>).generatePrivate(<span class="keyword">new</span> <span class="title class_">PKCS8EncodedKeySpec</span>(decoded));</span><br><span class="line">            <span class="comment">// RSA解密</span></span><br><span class="line">            <span class="type">Cipher</span> <span class="variable">cipher</span> <span class="operator">=</span> Cipher.getInstance(<span class="string">&quot;RSA&quot;</span>);</span><br><span class="line">            cipher.init(Cipher.DECRYPT_MODE, priKey);</span><br><span class="line">            <span class="type">byte</span>[] plainText = cipher.doFinal(Base64.getDecoder().decode(str));</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">String</span>(plainText, StandardCharsets.UTF_8);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException | NoSuchPaddingException | IllegalBlockSizeException |</span><br><span class="line">                 InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 随机生成密钥对</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> NoSuchAlgorithmException</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String[] genKeyPair() <span class="keyword">throws</span> NoSuchAlgorithmException &#123;</span><br><span class="line">        <span class="comment">// KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象</span></span><br><span class="line">        <span class="type">KeyPairGenerator</span> <span class="variable">keyPairGen</span> <span class="operator">=</span> KeyPairGenerator.getInstance(<span class="string">&quot;RSA&quot;</span>);</span><br><span class="line">        <span class="comment">// 初始化密钥对生成器</span></span><br><span class="line">        keyPairGen.initialize(<span class="number">1024</span>);</span><br><span class="line">        <span class="comment">// 生成一个密钥对，保存在keyPair中</span></span><br><span class="line">        <span class="type">KeyPair</span> <span class="variable">keyPair</span> <span class="operator">=</span> keyPairGen.generateKeyPair();</span><br><span class="line">        <span class="comment">// 得到私钥</span></span><br><span class="line">        <span class="type">RSAPrivateKey</span> <span class="variable">privateKey</span> <span class="operator">=</span> (RSAPrivateKey) keyPair.getPrivate();</span><br><span class="line">        <span class="comment">// 得到公钥</span></span><br><span class="line">        <span class="type">RSAPublicKey</span> <span class="variable">publicKey</span> <span class="operator">=</span> (RSAPublicKey) keyPair.getPublic();</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">publicKeyString</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(Base64.getEncoder().encode(publicKey.getEncoded()));</span><br><span class="line">        <span class="comment">// 得到私钥字符串</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">privateKeyString</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">String</span>(Base64.getEncoder().encode((privateKey.getEncoded())));</span><br><span class="line">        <span class="comment">// 将公钥和私钥保存到数组,0表示公钥,1表示私钥</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">String</span>[]&#123;publicKeyString, privateKeyString&#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        <span class="comment">// 生成公钥和私钥</span></span><br><span class="line"><span class="comment">//        String[] keyPair = genKeyPair();</span></span><br><span class="line"><span class="comment">//        String pubKey = keyPair[0];</span></span><br><span class="line"><span class="comment">//        String priKey = keyPair[1];</span></span><br><span class="line"><span class="comment">//        log.info(&quot;随机生成的公钥为: &#123;&#125;&quot;, pubKey);</span></span><br><span class="line"><span class="comment">//        log.info(&quot;随机生成的私钥为: &#123;&#125;&quot;, priKey);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 使用已生成的公钥和私钥，需要为PCKS#8格式，不要换行符\n</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">pubKey</span> <span class="operator">=</span> <span class="string">&quot;MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYahMu3WfdCHyyReESS9dP737U&quot;</span> +</span><br><span class="line">                <span class="string">&quot;ZeVsdLHofO7X8oKpM1QN2rk+mJKRgY58D5RS/UVAVWvHRH9E5hK8SWpiLRdbcWRP&quot;</span> +</span><br><span class="line">                <span class="string">&quot;bTYWO7EXokLN78QJXNfcA5HDnMBEaGi0FQp0cnY4DhlHcoov9luZzGWrnF6FJ6zV&quot;</span> +</span><br><span class="line">                <span class="string">&quot;aBY3fSnd0rpcifbtTwIDAQAB&quot;</span>;</span><br><span class="line">        <span class="type">String</span> <span class="variable">priKey</span> <span class="operator">=</span> <span class="string">&quot;MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJhqEy7dZ90IfLJF&quot;</span> +</span><br><span class="line">                <span class="string">&quot;4RJL10/vftRl5Wx0seh87tfygqkzVA3auT6YkpGBjnwPlFL9RUBVa8dEf0TmErxJ&quot;</span> +</span><br><span class="line">                <span class="string">&quot;amItF1txZE9tNhY7sReiQs3vxAlc19wDkcOcwERoaLQVCnRydjgOGUdyii/2W5nM&quot;</span> +</span><br><span class="line">                <span class="string">&quot;ZaucXoUnrNVoFjd9Kd3SulyJ9u1PAgMBAAECgYBS0MBfpJo89dGbpHCpWmBB5OZL&quot;</span> +</span><br><span class="line">                <span class="string">&quot;TpqclcPdiZTV7cWlXmh7pq8lHg311imvq19ywH+Sd1e6zLNCoqjnehS+B7Y6ePAJ&quot;</span> +</span><br><span class="line">                <span class="string">&quot;747l/SsLG4LBNO/D1ofS/d6RJv9SLGoE/7Q8q4qi8AqSPjI273jL+F4Zy6cwqzNP&quot;</span> +</span><br><span class="line">                <span class="string">&quot;UnMMrmzOsrmNLO2W0QJBAMi2vl0U28JmZnsCD7WzJfeuts0w7bYSE1JKKiHSc0Pn&quot;</span> +</span><br><span class="line">                <span class="string">&quot;Ih2GCk8qEbmvhTiUhVBqhlDT500Q4WxVC8FDSrm8VwUCQQDCZYMl5F6iSlSghI8R&quot;</span> +</span><br><span class="line">                <span class="string">&quot;uo6p4CMsRhIehWhJDyFAZ8BPXC8nYzbdJmzuEdZesJi/SUTbctBb9qmbCUNtd9Fl&quot;</span> +</span><br><span class="line">                <span class="string">&quot;hjtDAkEApg3qeH/lQHQPnP0bmivY4Y1+V0x/nf5eVdpd+RVvn2H964cVyGD5wTHh&quot;</span> +</span><br><span class="line">                <span class="string">&quot;eeoGUX2QGhb2ad/pYAMMcpwFmpyjMQJAWXO2xp/wgANuL7Lv1rue3EKcTMotmkfP&quot;</span> +</span><br><span class="line">                <span class="string">&quot;Nhc1ONrFHn+P3zMDUv5Uj7Q7jbT7hMIlYknR4Q9++i1oDp5dB7ed2wJAevVQ5LSH&quot;</span> +</span><br><span class="line">                <span class="string">&quot;5dNtsB8UE0vxiRXD0TYfSB2tcSIJ7TycB1GQFwdgqoouqRZ0SL5aV26xSDWvgCAz&quot;</span> +</span><br><span class="line">                <span class="string">&quot;qcGTGRvZN6c1jg==&quot;</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 加密字符串</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">message</span> <span class="operator">=</span> <span class="string">&quot;撒旦法多少发df阿斯蒂芬%… … ！@#￥%……&amp;*（）/*-!@#$%^&amp;*()爱的色放820&quot;</span>;</span><br><span class="line">        log.info(<span class="string">&quot;明文: &#123;&#125;&quot;</span>, message);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">messageEn</span> <span class="operator">=</span> encrypt(message, pubKey);</span><br><span class="line">        log.info(<span class="string">&quot;密文: &#123;&#125;&quot;</span>, messageEn);</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">messageDe</span> <span class="operator">=</span> decrypt(messageEn, priKey);</span><br><span class="line">        log.info(<span class="string">&quot;解密: &#123;&#125;&quot;</span>, messageDe);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-RSA加密解密（JavaScript）"><a href="#5-RSA加密解密（JavaScript）" class="headerlink" title="5. RSA加密解密（JavaScript）"></a>5. RSA加密解密（JavaScript）</h2><p>安装依赖</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install jsencrypt</span><br></pre></td></tr></table></figure>

<p>使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * RSA加密</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> str    明文</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> pubKey 公钥</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns</span> &#123;<span class="type">string | false</span>&#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">rsaEncrypt</span>(<span class="params">str, pubKey</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> jsEncrypt = <span class="keyword">new</span> <span class="title class_">JSEncrypt</span>();</span><br><span class="line">  jsEncrypt.<span class="title function_">setPublicKey</span>(pubKey);</span><br><span class="line">  <span class="keyword">return</span> jsEncrypt.<span class="title function_">encrypt</span>(str);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * RSA解密</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> str    密文</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> priKey 私钥</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns</span> &#123;<span class="type">string | false</span>&#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">rsaDecrypt</span>(<span class="params">str, priKey</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> jsEncrypt = <span class="keyword">new</span> <span class="title class_">JSEncrypt</span>();</span><br><span class="line">  jsEncrypt.<span class="title function_">setPrivateKey</span>(priKey);</span><br><span class="line">  <span class="keyword">return</span> jsEncrypt.<span class="title function_">decrypt</span>(str);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">rsaMain</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="comment">// 使用生成好的公钥和私钥，格式为PKCS#1或PKCS#8均可</span></span><br><span class="line">  <span class="keyword">const</span> pubKey = <span class="string">&#x27;MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYahMu3WfdCHyyReESS9dP737U&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;ZeVsdLHofO7X8oKpM1QN2rk+mJKRgY58D5RS/UVAVWvHRH9E5hK8SWpiLRdbcWRP&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;bTYWO7EXokLN78QJXNfcA5HDnMBEaGi0FQp0cnY4DhlHcoov9luZzGWrnF6FJ6zV&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;aBY3fSnd0rpcifbtTwIDAQAB&#x27;</span>;</span><br><span class="line">  <span class="keyword">const</span> priKey = <span class="string">&#x27;MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJhqEy7dZ90IfLJF&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;4RJL10/vftRl5Wx0seh87tfygqkzVA3auT6YkpGBjnwPlFL9RUBVa8dEf0TmErxJ&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;amItF1txZE9tNhY7sReiQs3vxAlc19wDkcOcwERoaLQVCnRydjgOGUdyii/2W5nM&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;ZaucXoUnrNVoFjd9Kd3SulyJ9u1PAgMBAAECgYBS0MBfpJo89dGbpHCpWmBB5OZL&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;TpqclcPdiZTV7cWlXmh7pq8lHg311imvq19ywH+Sd1e6zLNCoqjnehS+B7Y6ePAJ&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;747l/SsLG4LBNO/D1ofS/d6RJv9SLGoE/7Q8q4qi8AqSPjI273jL+F4Zy6cwqzNP&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;UnMMrmzOsrmNLO2W0QJBAMi2vl0U28JmZnsCD7WzJfeuts0w7bYSE1JKKiHSc0Pn&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;Ih2GCk8qEbmvhTiUhVBqhlDT500Q4WxVC8FDSrm8VwUCQQDCZYMl5F6iSlSghI8R&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;uo6p4CMsRhIehWhJDyFAZ8BPXC8nYzbdJmzuEdZesJi/SUTbctBb9qmbCUNtd9Fl&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;hjtDAkEApg3qeH/lQHQPnP0bmivY4Y1+V0x/nf5eVdpd+RVvn2H964cVyGD5wTHh&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;eeoGUX2QGhb2ad/pYAMMcpwFmpyjMQJAWXO2xp/wgANuL7Lv1rue3EKcTMotmkfP&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;Nhc1ONrFHn+P3zMDUv5Uj7Q7jbT7hMIlYknR4Q9++i1oDp5dB7ed2wJAevVQ5LSH&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;5dNtsB8UE0vxiRXD0TYfSB2tcSIJ7TycB1GQFwdgqoouqRZ0SL5aV26xSDWvgCAz&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;qcGTGRvZN6c1jg==&#x27;</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> text = <span class="string">&quot;阿什顿发asdfa1231@#$%^&amp;*(阿道夫（*……%￥%……&amp;asd安抚&quot;</span>;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[RSA]明文: &#x27;</span> + text);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 公钥加密</span></span><br><span class="line">  <span class="keyword">const</span> encrypted = <span class="title function_">rsaEncrypt</span>(text, pubKey);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[RSA]密文: &#x27;</span> + encrypted);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 私钥解密</span></span><br><span class="line">  <span class="keyword">const</span> decrypted = <span class="title function_">rsaDecrypt</span>(encrypted, priKey);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;[RSA]解密: &#x27;</span> + decrypted);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">rsaMain</span>();</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="reward-container">
  <div>请我一杯咖啡吧！</div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.jpg" alt="du qian 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.jpg" alt="du qian 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%8A%A0%E5%AF%86/" rel="tag"># 加密</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/12/26/home-network/" rel="prev" title="家庭网络重新布线">
                  <i class="fa fa-angle-left"></i> 家庭网络重新布线
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/02/15/k8s-custom-dns-and-hosts/" rel="next" title="k8s-自定义DNS和hosts">
                  k8s-自定义DNS和hosts <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">冀ICP备17034993号-1 </a>
  </div>
  <div class="copyright">
    &copy; 2016 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">du qian</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>
  <div class="upyun-league">
    本网站由<a target="_blank" rel="noopener" href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" style="border-bottom: none;">
      <img src="/images/upyun_logo.png" alt="又拍云" style="display: inline;height: 30px;vertical-align: bottom;"/>
    </a>提供CDN加速/云存储服务
  </div>


    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/duqian42707" class="github-corner" title="在 GitHub 上关注我" aria-label="在 GitHub 上关注我" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>


  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":"forest","js":{"url":"/lib/mermaid/dist/mermaid.min.js","integrity":"sha256-G8ouPAnw4zzMbnAenHnVz6h9XpKbNdOkrqTh7AadyHs="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>





  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<link rel="stylesheet" href="/lib/gitalk/dist/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"duqian42707","repo":"blog-comment","client_id":"c9f48bc2fea3d4ce5d93","client_secret":"154d6227d3d7b532b36bfc1ce030121f0263ac90","admin_user":"duqian42707","distraction_free_mode":false,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","js":{"url":"/lib/gitalk/dist/gitalk.min.js","integrity":"sha256-MVK9MGD/XJaGyIghSVrONSnoXoGh3IFxLw0zfvzpxR4="},"path_md5":"1d59d55a0d2a0a376eaf51c178b76bb5"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>

</body>
</html>
